<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>树莓派小车控制中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        header {
            text-align: center;
            margin-bottom: 20px;
            padding: 20px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 15px;
        }
        
        h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        
        .video-section {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 15px;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .video-container {
            width: 100%;
            max-width: 800px;
            height: 450px;
            background: black;
            border-radius: 10px;
            overflow: hidden;
            position: relative;
        }
        
        #videoStream {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        
        .controls-section {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .control-panel {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 15px;
            padding: 20px;
        }
        
        .panel-title {
            font-size: 1.3em;
            margin-bottom: 15px;
            text-align: center;
            color: #ffeb3b;
        }
        
        /* WASD 控制器样式 */
        .wasd-controls {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 10px;
            max-width: 250px;
            margin: 0 auto;
        }
        
        .btn {
            width: 70px;
            height: 70px;
            font-size: 18px;
            font-weight: bold;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.4);
        }
        
        .btn:active {
            transform: translateY(1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        
        .btn-up { grid-column: 2; grid-row: 1; background: linear-gradient(45deg, #2196F3, #1976D2); }
        .btn-left { grid-column: 1; grid-row: 2; background: linear-gradient(45deg, #ff9800, #f57c00); }
        .btn-stop { grid-column: 2; grid-row: 2; background: linear-gradient(45deg, #f44336, #d32f2f); }
        .btn-right { grid-column: 3; grid-row: 2; background: linear-gradient(45deg, #9c27b0, #7b1fa2); }
        .btn-down { grid-column: 2; grid-row: 3; background: linear-gradient(45deg, #607d8b, #455a64); }

        /* 拍照 & 激光按钮通用样式 */
        .action-btn {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s;
        }
        .photo-btn { background: linear-gradient(45deg, #00bcd4, #0097a7); color: white; }
        .laser-on-btn { background: linear-gradient(45deg, #4caf50, #388e3c); color: white; }
        .laser-off-btn { background: linear-gradient(45deg, #f44336, #d32f2f); color: white; }
        
        /* 速度控制样式 */
        .speed-control {
            text-align: center;
        }
        
        .speed-slider {
            width: 100%;
            margin: 15px 0;
        }
        
        .speed-value {
            font-size: 1.2em;
            font-weight: bold;
            color: #ffeb3b;
        }
        
        /* 舵机控制样式 */
        .servo-control {
            text-align: center;
        }
        
        .servo-inputs {
            display: flex;
            gap: 10px;
            margin: 15px 0;
            justify-content: center;
        }
        
        .servo-input {
            width: 60px;
            padding: 8px;
            border: none;
            border-radius: 5px;
            text-align: center;
            font-size: 16px;
        }
        
        .servo-btn {
            padding: 8px 16px;
            background: linear-gradient(45deg, #ff5722, #e64a19);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
        }
        
        .status-bar {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 15px;
            padding: 15px;
            text-align: center;
            margin-top: 20px;
            font-size: 1.1em;
        }
        
        .status-text {
            color: #4caf50;
            font-weight: bold;
        }
        
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        
        .key-guide {
            margin-top: 15px;
            font-size: 0.9em;
            color: #ccc;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🤖 树莓派小车控制中心</h1>
            <p>实时视频流 + 远程控制</p>
        </header>
        
        <div class="main-content">
            <div class="video-section">
                <h2>实时视频流（带目标检测）</h2>
                <div class="video-container">
                    <img id="videoStream" src="http://192.168.43.112:8080/?action=stream" alt="Detected Video Stream">
                </div>
                <div class="key-guide">
                    <p>视频流地址: http://localhost:5001/detected_feed</p>
                </div>
            </div>
            
            <div class="controls-section">
                <!-- 拍照功能 -->
                <div class="control-panel">
                    <h3 class="panel-title">📸 拍照功能</h3>
                    <div style="text-align: center;">
                        <button class="action-btn photo-btn" id="snapshotBtn">📷 拍照</button>
                    </div>
                </div>

                <!-- 激光控制 -->
                <div class="control-panel">
                    <h3 class="panel-title">🔦 激光控制</h3>
                    <div style="text-align: center;">
                        <button class="action-btn laser-on-btn" id="laserOnBtn">🟢 开启激光</button>
                        <button class="action-btn laser-off-btn" id="laserOffBtn">🔴 关闭激光</button>
                    </div>
                </div>

                <!-- WASD 控制器 -->
                <div class="control-panel">
                    <h3 class="panel-title">🚀 移动控制</h3>
                    <div class="wasd-controls">
                        <button class="btn btn-up" id="forwardBtn">W<br>↑</button>
                        <button class="btn btn-left" id="leftBtn">A<br>←</button>
                        <button class="btn btn-stop" id="stopBtn">■<br>停</button>
                        <button class="btn btn-right" id="rightBtn">D<br>→</button>
                        <button class="btn btn-down" id="backwardBtn">S<br>↓</button>
                    </div>
                    <div class="key-guide">
                        <p>键盘快捷键: WASD + 空格键停止</p>
                    </div>
                </div>
                
                <!-- 速度控制 -->
                <div class="control-panel">
                    <h3 class="panel-title">⚡ 速度调节</h3>
                    <div class="speed-control">
                        <input type="range" id="speedSlider" class="speed-slider" min="0" max="100" value="50">
                        <div class="speed-value">当前速度: <span id="speedValue">50</span>%</div>
                    </div>
                </div>
                
                <!-- 舵机控制 -->
                <div class="control-panel">
                    <h3 class="panel-title">🔧 舵机控制</h3>
                    <div class="servo-control">
                        <div class="servo-inputs">
                            <input type="number" id="servoNum" class="servo-input" min="1" max="4" value="1" placeholder="舵机号">
                            <input type="number" id="servoAngle" class="servo-input" min="0" max="180" value="90" placeholder="角度">
                        </div>
                        <button class="servo-btn" id="setServoBtn">设置舵机</button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="status-bar">
            <div class="status-text" id="status">就绪 - 点击按钮开始控制</div>
        </div>

    <script>
        // 服务器地址 - 请修改为您的树莓派实际IP地址
        const SERVER_URL = 'http://192.168.43.112:5000';
        const STREAM_URL = 'http://192.168.43.112:8080';
        
        // 获取DOM元素
        const forwardBtn = document.getElementById('forwardBtn');
        const backwardBtn = document.getElementById('backwardBtn');
        const leftBtn = document.getElementById('leftBtn');
        const rightBtn = document.getElementById('rightBtn');
        const stopBtn = document.getElementById('stopBtn');
        const speedSlider = document.getElementById('speedSlider');
        const speedValue = document.getElementById('speedValue');
        const statusDiv = document.getElementById('status');
        const servoNumInput = document.getElementById('servoNum');
        const servoAngleInput = document.getElementById('servoAngle');
        const setServoBtn = document.getElementById('setServoBtn');
        const snapshotBtn = document.getElementById('snapshotBtn');
        const laserOnBtn = document.getElementById('laserOnBtn');
        const laserOffBtn = document.getElementById('laserOffBtn');
        
        // 设置按钮加载状态
        function setButtonLoading(isLoading) {
            const buttons = document.querySelectorAll('.btn, .servo-btn, .action-btn');
            buttons.forEach(btn => {
                if (isLoading) {
                    btn.classList.add('loading');
                } else {
                    btn.classList.remove('loading');
                }
            });
        }
        
        // 发送控制命令的函数
        async function sendCommand(endpoint, data = null) {
            try {
                setButtonLoading(true);
                statusDiv.textContent = '正在执行命令...';
                
                let response;
                if (data) {
                    response = await fetch(`${SERVER_URL}${endpoint}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(data)
                    });
                } else {
                    response = await fetch(`${SERVER_URL}${endpoint}`);
                }
                
                const result = await response.json();
                statusDiv.textContent = '状态: ' + result.status;
                console.log('命令执行成功:', result);
                
                return result;
                
            } catch (error) {
                statusDiv.textContent = '错误: 无法连接到服务器';
                console.error('请求失败:', error);
                return null;
            } finally {
                setTimeout(() => {
                    setButtonLoading(false);
                }, 500);
            }
        }

        // ✅ 拍照功能：不显示，直接下载
        snapshotBtn.addEventListener('click', () => {
            const timestamp = new Date().getTime();
            const snapshotUrl = `${STREAM_URL}/?action=snapshot&_t=${timestamp}`;
            
            // 创建临时 a 标签触发下载
            const a = document.createElement('a');
            a.href = snapshotUrl;
            a.download = `snapshot_${timestamp}.jpg`; // 用户下载文件名
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            
            statusDiv.textContent = '已拍照并下载';
        });

        // 激光控制
        laserOnBtn.addEventListener('click', () => {
            sendCommand('/laser_on');
        });

        laserOffBtn.addEventListener('click', () => {
            sendCommand('/laser_off');
        });
        
        // 为按钮添加事件监听器
        forwardBtn.addEventListener('click', () => sendCommand('/forward'));
        backwardBtn.addEventListener('click', () => sendCommand('/backward'));
        leftBtn.addEventListener('click', () => sendCommand('/left'));
        rightBtn.addEventListener('click', () => sendCommand('/right'));
        stopBtn.addEventListener('click', () => sendCommand('/stop'));
        
        // 速度滑块控制
        speedSlider.addEventListener('input', function() {
            const speed = parseInt(this.value);
            speedValue.textContent = speed;
            sendCommand('/set_speed', { speed: speed });
        });
        
        // 舵机控制
        setServoBtn.addEventListener('click', function() {
            const servoNum = parseInt(servoNumInput.value);
            const angle = parseInt(servoAngleInput.value);
            
            if (isNaN(servoNum) || isNaN(angle)) {
                statusDiv.textContent = '错误: 请输入有效的舵机号和角度';
                return;
            }
            
            if (servoNum < 1 || servoNum > 4) {
                statusDiv.textContent = '错误: 舵机号必须在1-4之间';
                return;
            }
            
            if (angle < 0 || angle > 180) {
                statusDiv.textContent = '错误: 角度必须在0-180之间';
                return;
            }
            
            sendCommand('/set_servo', { 
                servo_num: servoNum, 
                angle: angle 
            });
        });
        
        // 键盘控制支持
        document.addEventListener('keydown', (event) => {
            switch(event.key.toLowerCase()) {
                case 'w':
                    event.preventDefault();
                    sendCommand('/forward');
                    break;
                case 's':
                    event.preventDefault();
                    sendCommand('/backward');
                    break;
                case 'a':
                    event.preventDefault();
                    sendCommand('/left');
                    break;
                case 'd':
                    event.preventDefault();
                    sendCommand('/right');
                    break;
                case ' ':
                    event.preventDefault();
                    sendCommand('/stop');
                    break;
            }
        });
        
        // 页面加载完成初始化
        window.addEventListener('load', () => {
            const videoImg = document.getElementById('videoStream');
            videoImg.onerror = function() {
                statusDiv.textContent = '警告: 无法加载视频流，请检查摄像头服务';
                videoImg.style.backgroundColor = '#333';
                videoImg.alt = '视频流加载失败';
            };
            
            setTimeout(() => {
                statusDiv.textContent = '就绪 - 点击按钮开始控制';
            }, 1000);
        });
    </script>
</body>
</html>